package home

func next8(p, n int8) int8 {
	// 因为其他版本不仅仅取一位，就不以 (p>>2)&1 的格式写
	b2 := (p & 4) >> 2
	b1 := (n & 2) >> 1
	b0 := n & 1
	return ((b2 ^ b1 ^ b0) << 2) | ((b2 & b0) << 1) | (b2 | b1)
}

const nerr = (1 << 64) - 1
const serr = "_"
const nmax = 1 << 60
const byte5_len = 20

func Convert_htr_64(htr string) uint64 {
	if len(htr) == 0 || len(htr) > byte5_len {
		return uint64(nerr)
	}
	var r uint64 = 0
	for _, s := range htr {
		r = r << 3
		switch s {
		case '0':
		case '1':
			r = r | 1
		case '2':
			r = r | 3
		case '3':
			r = r | 4
		case '4':
			r = r | 5
		case '5':
			r = r | 7
		default:
			return uint64(nerr)
		}
	}
	return r
}

func Convert_64_htr(hex uint64) string {
	if hex == 0 {
		return "0"
	}
	if hex >= nmax {
		return serr
	}

	bytes := make([]byte, byte5_len)
	count := 1
	for hex > 0 {
		h := hex & 0b111
		switch h {
		case 0:
			bytes[byte5_len-count] = '0'
		case 1:
			bytes[byte5_len-count] = '1'
		case 3:
			bytes[byte5_len-count] = '2'
		case 4:
			bytes[byte5_len-count] = '3'
		case 5:
			bytes[byte5_len-count] = '4'
		case 7:
			bytes[byte5_len-count] = '5'
		default:
			return serr
		}
		hex = hex >> 3
		count++
	}
	return string(bytes[byte5_len-count+1 : byte5_len])
}
